<template>
  <div class="alarmConfiguration zy-content">
    <!-- 搜索 -->
    <search :columns="searchData" @getSearch="getSearch(arguments)" key="search"></search>
    <div class="alarmConfiguration">
      <div class="list-layout mt16">
        <!-- 批量删除 批量导出  批量导入 下载模板 新增-->
        <div class="btns clear">
          <span class="title">{{ $t('common.listInformation') }}</span>
          <Button @click="createfaultCodeShowH" v-if="checkBtnPermission.moldLedgerAddBtn">{{
              $t('common.New')
            }}
          </Button>
          <Button @click="delFaultCodeShowClick" v-if="checkBtnPermission.moldLedgerBatchDelBtn"
                  v-has="'moldLedgerBatchDelBtn'">{{
              $t('common.batchDelete')
            }}
          </Button>
          <!-- 添加批量打印按钮 -->
          <Button @click="batchPrint">批量打印
          </Button>
          <Button @click="exportTemplateClick" v-if="checkBtnPermission.moldLedgerExport">{{
              $t('common.Export')
            }}
          </Button>
          <Button @click="importExcelShow" v-if="checkBtnPermission.moldLedgerImport">导入</Button>
          <Button @click="exportTemplate" v-if="checkBtnPermission.moldLedgerDownload">{{
              $t('common.Download')
            }}
          </Button>
          <Button @click="getTableColumns(columns)">
            {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}
          </Button>
        </div>
        <!-- 表格 -->
        <div class="tableContent">
          <Table
              class="resizable-table"
              border
              @on-column-width-resize="onColumnWidthResize"
              :columns="columnsList"
              ellipsis
              ref="selection"
              stripe
              :data="dataArr"
              @on-selection-change="onSelectChange"
          >
            <template slot-scope="{ row }" slot="status">
              <span>
                {{ row.status == 1 ? '启用' : '禁用' }}
              </span>
            </template>
            <template slot-scope="{ row }" slot="action">
              <span class="operationBtn" @click="check(row)"><i
                  class="iconfont zy-common-chakan"></i>{{ $t('common.Check') }}</span>
              <span class="operationBtn" @click="checkMore(row)"><i class="iconfont zy-common-chakan"></i>履历</span>
              <Dropdown
                  transfer-class-name="theme-dropdown"
                  :transfer="true"
                  placement="left-start">
                <a href="javascript:void(0)">
                  <i class="iconfont zy-common-gengduo1"></i>
                  {{ $t("common.more") }}
                  <Icon type="arrow-down-b"></Icon>
                </a>
                <Dropdown-menu slot="list">
                  <Dropdown-item
                      v-if="checkBtnPermission.moldLedgerEdit"
                      @click.native="createfaultCodeShowH(row)"
                  >
                    <span class="operationBtn">{{ $t('common.Edit') }}</span>
                  </Dropdown-item>
                  <Dropdown-item
                      @click.native="handlePrint(row)"
                  >
                    <span class="operationBtn">{{ $t("preliminary.PrintQRCode") }}</span>
                  </Dropdown-item>
                  <Dropdown-item
                      v-if="checkBtnPermission.moldLedgerDelBtn"
                      @click.native="delPrrShowH(row)"
                  >
                    <span class="operationBtn">{{ $t('common.Delete') }}</span>
                  </Dropdown-item>

                  <Dropdown-item
                      @click.native="updateStatus(row, row.status == 1 ? 0 : 1)"
                  >
                    <span class="operationBtn">{{ row.status == 1 ? '禁用' : '启用' }}</span>
                  </Dropdown-item>

                </Dropdown-menu>
              </Dropdown>
            </template>
            <template slot-scope="{ row }" slot="productionMode">
              <span class="operationBtn" style="color: #3271f0" @click="showMc(row)">{{ row.productionMode }}</span>
            </template>
          </Table>
        </div>
        <Modal :mask-closable="false" v-model="mcShow" title="单次刃磨寿命清单" class="modal-content-layout" width="55%">
          <div class="alarmConfiguration">
            <div class="list-layout2">
              <!-- 表格 -->
              <div class="tableContent mt14">
                <Table
                    class="resizable-table"
                    border
                    @on-column-width-resize="onColumnWidthResize"
                    :columns="mcColumns"
                    ellipsis
                    ref="selection"
                    stripe
                    :data="mcData"
                >
                </Table>
              </div>
              <!-- 分页 -->
              <div class="pageWrap mt16">
                <pageLeftTitle :total="mcTotal" selected="0"/>
                <Page
                    :total="mcTotal"
                    :page-size="mcPageSize"
                    :page-size-opts="pageSizeOption"
                    :current="mcPageNum"
                    @on-change="changePageNum2"
                    @on-page-size-change="changePageSize2"
                    show-sizer
                    show-total
                />
              </div>
            </div>
          </div>
          <div slot="footer">
            <Button type="default" @click="mcShow = false">{{ $t('common.Cancle') }}</Button>
          </div>
        </Modal>
        <!-- 分页 -->
        <div class="pageWrap mt16">
          <pageLeftTitle :total="total" :selected="delIds.length"/>
          <Page
              :total="total"
              :page-size="pageSize"
              :page-size-opts="pageSizeOption"
              :current="pageNum"
              @on-change="changePageNum"
              @on-page-size-change="changePageSize"
              show-sizer
              show-total
          />
        </div>
      </div>
      <!-- 新增编辑 -->
      <Modal :mask-closable="false" v-model="create" :title="addtitle" class="modal-content-layout" width="80%">
        <div class="content-item">
          <Row>
            <Col class="pd16">
              <Form ref="form" :disabled="disabled" class="formList" :model="formItem" label-position="top"
                    :rules="ruleValidate">
                <Row :gutter="20">
                  <Col span="8">
                    <FormItem label="模具名称" prop="moldName">
                      <Input type="text" v-model="formItem.moldName" :placeholder="`${$t('common.inputInfo')}`"/>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="资产编号" prop="assetCode">
                      <Input type="text" v-model="formItem.assetCode" :placeholder="`${$t('common.inputInfo')}`"/>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="模具编号" prop="moldCode">
                      <Input type="text" :readonly="addtitle == '编辑'" v-model="formItem.moldCode"
                             :placeholder="`${$t('common.inputInfo')}`"/>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="模具类型" prop="moldModel">
                      <Input type="text" v-model="formItem.moldModel" :placeholder="`${$t('common.inputInfo')}`"/>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="模具状态" prop="moldState">
                      <Select v-model="formItem.moldState" filterable clearable :max-tag-count="1"
                              :placeholder="`${$t('common.selectInfo')}`">
                        <Option v-for="item of moldStateList" :value="item.value" :key="item.value"
                                :label="item.value"></Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="理论节拍(spm)" prop="moldingCycle">
                      <Input
                          type="number"
                          v-model="formItem.moldingCycle"
                          :min="0"
                          @on-keyup="keyUp5($event, 'moldingCycle', true)"
                          :max="999999"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                      </Input>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="型腔数" prop="cavityNum">
                      <InputNumber
                          type="number"
                          :max="100"
                          :step="1"
                          :min="0"
                          v-model="formItem.cavityNum"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                      </InputNumber>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="模具寿命" prop="moldLife">
                      <InputNumber
                          type="number"
                          :max="99999999"
                          :step="1"
                          :min="0"
                          v-model="formItem.moldLife"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                      </InputNumber>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="模具位置" prop="workShopList">
                      <Cascader
                          clearable
                          :data="orgList"
                          v-model="formItem.workShopList"
                          :placeholder="`${$t('common.selectInfo')}`"
                          change-on-select
                      >
                      </Cascader>
                    </FormItem>
                    <!-- <FormItem label="生产模数" prop="productionMode">
                      <Input
                        type="number"
                        @on-keyup="keyUp($event, 'productionMode', true)"
                        v-model="formItem.productionMode"
                        :placeholder="`${$t('common.inputInfo')}`"
                      >
                      </Input>
                    </FormItem> -->
                  </Col>
                  <Col span="8">
                    <FormItem label="库区" prop="reservoirArea">
                      <Select
                          v-model="formItem.reservoirAreaId"
                          filterable
                          clearable
                          :placeholder="`${$t('common.selectInfo')}`"
                          @on-change="handleReservoirChange"
                      >
                        <Option
                            v-for="item in reservoirAreaList"
                            :value="item.id"
                            :key="item.id"
                        >{{ item.mreservoir }} - {{ item.mwarehouse }}</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="库位" prop="warehouseLocation">
                      <Input
                          v-model="formItem.warehouseLocation"
                          :placeholder="`${$t('common.inputInfo')}`"
                          :disabled="!formItem.reservoirArea"
                      />
                    </FormItem>
                  </Col>

                  <Col span="8">
                    <FormItem label="二级保养模次" prop="messageMaintenanceMode">
                      <InputNumber
                          type="number"
                          :max="99999999"
                          :min="0"
                          onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
                          v-model="formItem.messageMaintenanceMode"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                      </InputNumber>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="二级实际保养模次" prop="maintenanceMode">
                      <InputNumber
                          type="number"
                          :max="99999999"
                          :min="0"
                          onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
                          v-model="formItem.maintenanceMode"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                      </InputNumber>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="三级保养模次" prop="messageMaintenanceModeThree">
                      <InputNumber
                          type="number"
                          :max="99999999"
                          :min="0"
                          onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
                          v-model="formItem.messageMaintenanceModeThree"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                      </InputNumber>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="三级实际保养模次" prop="maintenanceModeThree">
                      <InputNumber
                          type="number"
                          :max="99999999"
                          :min="0"
                          onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
                          v-model="formItem.maintenanceModeThree"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                      </InputNumber>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="评分" prop="score">
                      <InputNumber
                          type="number"
                          onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
                          :max="100"
                          :min="0"
                          v-model="formItem.score"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                      </InputNumber>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="条料宽度" prop="stripWidth">
                      <Input
                          type="number"
                          @on-keyup="keyUp($event, 'stripWidth', true)"
                          v-model="formItem.stripWidth"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                        <span slot="append">mm</span>
                      </Input>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="送料步长" prop="lengths">
                      <Input
                          type="number"
                          @on-keyup="keyUp($event, 'lengths', true)"
                          v-model="formItem.lengths"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                        <span slot="append">mm</span>
                      </Input>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="条料厚度" prop="thickness">
                      <Input
                          type="number"
                          @on-keyup="keyUp($event, 'thickness', true)"
                          v-model="formItem.thickness"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                        <span slot="append">mm</span>
                      </Input>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="模具重量" prop="moldWeight">
                      <Input
                          type="number"
                          @on-keyup="keyUp($event, 'moldWeight', true)"
                          v-model="formItem.moldWeight"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                        <span slot="append">吨</span>
                      </Input>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="闭模高度" prop="closedMoldHeight">
                      <Input
                          type="number"
                          @on-keyup="keyUp($event, 'closedMoldHeight', true)"
                          v-model="formItem.closedMoldHeight"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                        <span slot="append">mm</span>
                      </Input>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="外形尺寸" prop="externalDimensions">
                      <InputNumber :min="0" v-model="formItem.externalDimensions" :max="99999999999"
                                   :placeholder="`${$t('common.inputInfo')}`">
                      </InputNumber>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="投用日期" prop="useDate">
                      <DatePicker
                          format="yyyy-MM-dd"
                          :value="formItem.useDate"
                          @on-change="
													(val) => {
														formItem.useDate = val;
													}
												"
                          type="date"
                          split-panels
                          :placeholder="`${$t('common.selectInfo')}`"
                      ></DatePicker>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="验收日期" prop="acceptDate">
                      <DatePicker
                          format="yyyy-MM-dd"
                          :value="formItem.acceptDate"
                          @on-change="
													(val) => {
														formItem.acceptDate = val;
													}
												"
                          type="date"
                          split-panels
                          :placeholder="`${$t('common.selectInfo')}`"
                      ></DatePicker>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="制造年月" prop="manufactureDate">
                      <DatePicker
                          format="yyyy-MM-dd"
                          :value="formItem.manufactureDate"
                          @on-change="
													(val) => {
														formItem.manufactureDate = val;
													}
												"
                          type="date"
                          split-panels
                          :placeholder="`${$t('common.selectInfo')}`"
                      ></DatePicker>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="RFID编码" prop="rfidEncoding">
                      <Input v-model="formItem.rfidEncoding" :placeholder="`${$t('common.inputInfo')}`"> </Input>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="利用率(%)" prop="useRate">
                      <InputNumber
                          type="number"
                          v-model="formItem.useRate"
                          :precision="2"
                          :max="100"
                          :min="0"
                          :active-change="false"
                          :placeholder="`${$t('common.inputInfo')}`"
                      >
                        <span slot="append">%</span>
                      </InputNumber>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="加工厂家" prop="processingManufacturer">
                      <Input type="text" v-model="formItem.processingManufacturer"
                             :placeholder="`${$t('common.inputInfo')}`"/>
                    </FormItem>
                  </Col>
                  <Col span="24">
                    <FormItem label="备注" prop="remarks">
                      <Input
                          type="textarea"
                          :autosize="{ minRows: 1, maxRows: 3 }"
                          v-model="formItem.remarks"
                          :placeholder="`${$t('common.inputInfo')}`"
                      />
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Col>
          </Row>
        </div>
        <div slot="footer">
          <Button type="default" @click="create = false">{{ $t('common.Cancle') }}</Button>
          <Button type="primary" v-if="!disabled" :loading="loading" @click="addOk('form')">
            {{ $t('maintenance.Confirmed') }}
          </Button>
        </div>
      </Modal>
      <!-- 请确认是否删除弹框 -->
      <Modal :mask-closable="false" v-model="delFaultCodeShowF" :title="$t('common.Delete')" class="modal-title-layout">
        <div class="icon red">
          <i class="iconfont zy-common-shanchu"></i>
        </div>
        <p class="title">
          <span>{{ $t('common.confirmDelete') }}</span>
        </p>
        <div slot="footer">
          <Button type="default" @click="delFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
          <Button type="primary" :loading="loading" @click="deleteOk">{{ $t('maintenance.Confirmed') }}</Button>
        </div>
      </Modal>
      <importExcelModal
          :importExcelStateF="importExcelState"
          v-if="importExcelState"
          url="/dms/moldinfo/import"
          @importExcelChange="importExcelChange"
      ></importExcelModal>
    </div>

    <ledger-print-modal ref="ledgerPrintModal"/>

  </div>
</template>

<script>
import {searchApi, addApi, editApi, deleteApi, templateApi, exportApi} from '@/api/moldManagement/moldLedger.js';
import {getUserSelect, getDictData} from '@/api/index.js';
import search from '@/components/curd/searchList.vue';
import importExcelModal from '@/components/importExcelNew.vue';
import fileDownload from 'js-file-download';
import toggleTableOperation from '@/mixins/toggleTableOperation';
import {InputNumber} from 'view-design';
import recursion from '@/util/recursion';
import {updateStatusLedgerApi} from "@/api/spareParts/storeHouse";
import ledgerPrintModal from "./modules/ledgerPrintModal";
import request from "@/axios/axios";

export default {
  name: 'storeHouse', //仓库配置
  components: {importExcelModal, search, InputNumber, ledgerPrintModal},
  mixins: [toggleTableOperation],
  data() {
    const validateNumber = (rule, val, callback, message) => {
      if (val !== '') {
        return callback();
      }
      return callback(new Error(message));
    };
    return {
      orgList: [],
      searchData: [
        {
          title: '模具名称',
          key: 'moldName',
        },
        {
          title: '模具编号',
          key: 'moldCode',
        },
        {
          title: '模具类型',
          key: 'moldModel',
        },
        {
          title: '资产编号',
          key: 'assetCode',
        },
        {
          title: '模具等级',
          key: 'moldGrade',
          type: 'select',
          dicData: [
            {label: 'A', value: 'A'},
            {label: 'B', value: 'B'},
            {label: 'C', value: 'C'},
          ],
        },
        {
          title: '模具状态',
          key: 'moldStateList',
          type: 'select',
          multiple: true,
          dicUrl: '/dms/faultCategory/dictList?name=模具状态',
          params: {
            label: 'value',
            value: 'value',
          },
          // dicData:this.moldStateList
        },
        {
          title: '功能位置',
          key: 'functionalLocationName',
          type: 'cascader',
          dicUrl: '/basic/organization/findListByToken?level=0',
          params: {
            label: 'name',
            value: 'code',
            children: 'children',
          },
        },
        {
          title: '状态',
          key: 'status',
          type: 'select',
          dicData: [
            {label: '启用', value: 1},
            {label: '禁用', value: 0},
          ],
        }
      ],
      mcColumns: [
        {
          title: '序号',
          width: 80,
          align: 'center',
          render: (h, params) => {
            return h('span', params.index + (this.mcPageNum - 1) * this.mcPageSize + 1);
          },
        },
        {
          title: '时间',
          key: 'moldState',
          minWidth: 150,
          align: 'center',
          resizable: true,
          tooltip: true,
        },

        {
          title: '当班产量',
          key: 'assetCode',
          minWidth: 150,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '产量累计',
          key: 'moldCode',
          minWidth: 150,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '备注',
          key: 'moldName',
          minWidth: 150,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
      ],
      columns: [
        {
          key: 'selection',
          type: 'selection',
          width: 60,
          align: 'center',
        },
        {
          title: '模具状态',
          key: 'moldState',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },

        {
          title: '资产编号',
          key: 'assetCode',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '模具编号',
          key: 'moldCode',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '模具名称',
          key: 'moldName',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '模具类型',
          key: 'moldModel',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '生产模次',
          key: 'productionMode',
          minWidth: 100,
          // slot: 'productionMode',
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '二级保养模次',
          key: 'messageMaintenanceMode',
          minWidth: 160,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '二级实际保养模次',
          key: 'maintenanceMode',
          minWidth: 160,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '三级保养模次',
          key: 'messageMaintenanceModeThree',
          minWidth: 160,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '三级实际保养模次',
          key: 'maintenanceModeThree',
          minWidth: 160,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '模具等级',
          key: 'moldGrade',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '评分',
          key: 'score',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '日定额',
          key: 'dayQuota',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '工时定额（PCS/H）',
          key: 'hourQuota',
          minWidth: 189,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '理论节拍(S)',
          key: 'moldingCycle',
          minWidth: 120,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '型腔数',
          key: 'cavityNum',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '模具寿命',
          key: 'moldLife',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '模具剩余寿命',
          key: 'moldResidueLife',
          minWidth: 130,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '功能位置',
          key: 'functionLocation',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '库区',
          key: 'reservoirArea',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '库位',
          key: 'warehouseLocation',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '加工厂家',
          key: 'processingManufacturer',
          minWidth: 100,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '条料宽度(mm)',
          key: 'stripWidth',
          minWidth: 140,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '送料步长(mm)',
          key: 'lengths',
          minWidth: 140,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '条料厚度(mm)',
          key: 'thickness',
          minWidth: 140,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '模具重量(吨)',
          key: 'moldWeight',
          minWidth: 140,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '闭模高度(mm)',
          key: 'closedMoldHeight',
          minWidth: 140,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '外形尺寸',
          key: 'externalDimensions',
          minWidth: 140,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: 'RFID编码',
          key: 'rfidEncoding',
          minWidth: 140,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '利用率',
          key: 'useRate',
          minWidth: 140,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: "状态",
          slot: "status",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          title: '操作',
          slot: 'action',
          fixed: 'right',
          minWidth: 260,
          align: 'center',
        },
      ],
      checkBtnPermission: {},
      ruleValidate: {
        moldName: [{required: true, message: this.$t('common.inputInfo')}],
        moldCode: [{required: true, message: this.$t('common.inputInfo')}],
        moldModel: [{required: true, message: this.$t('common.inputInfo')}],
        cavityNum: [{required: true, message: this.$t('common.inputInfo')}],
        messageMaintenanceMode: [{required: true, message: this.$t('common.inputInfo')}],
        messageMaintenanceModeThree: [{required: true, message: this.$t('common.inputInfo')}],
        maintenanceMode: [{required: true, message: this.$t('common.inputInfo')}],
        maintenanceModeThree: [{required: true, message: this.$t('common.inputInfo')}],
        useRate: [{required: true, message: '请输入利用率', type: 'number'}],
        moldingCycle: [{required: true, validator: validateNumber, message: this.$t('common.inputInfo')}],
        score: [{required: true, message: this.$t('common.inputInfo')}],
        moldState: [{required: true, message: this.$t('common.selectInfo')}],
      },
      moldStateList: [],
      disabled: false,
      backupList: [],
      shelfList: [],
      locationList: [],
      importExcelState: false /*批量导入*/,
      formItem: {},
      addtitle: '',
      allCheck: false,
      loading: false,
      create: false,
      searchParams: {},
      pageNum: 1,
      pageSize: 10,
      total: 0,
      dataArr: [],
      delFaultCodeShowF: false, //是否显示删除弹窗
      pageSizeOption: [10, 20, 30, 40],
      delIds: [],
      selection: [],
      createByOptions: [],
      mcShow: false,
      mcPageSize: 10,
      mcPageNum: 1,
      mcTotal: 0,
      reservoirAreaList:[]
    };
  },
  mounted() {
    this.getTableColumnsWidth(this.columns);
    this.searchList();
    this.getOrgList();

    this.getUserList();
    getDictData('模具状态').then((res) => {
      this.moldStateList = res.data;
    });
    let itemList = JSON.parse(window.localStorage.getItem('USER_URI'));
    for (let item of itemList) {
      if (item.code == 'moldLedgerAddBtn') {
        this.checkBtnPermission.moldLedgerAddBtn = true;
      }
      if (item.code == 'moldLedgerBatchDelBtn') {
        this.checkBtnPermission.moldLedgerBatchDelBtn = true;
      }
      if (item.code == 'moldLedgerExport') {
        this.checkBtnPermission.moldLedgerExport = true;
      }
      if (item.code == 'moldLedgerImport') {
        this.checkBtnPermission.moldLedgerImport = true;
      }
      if (item.code == 'moldLedgerDownload') {
        this.checkBtnPermission.moldLedgerDownload = true;
      }
      if (item.code == 'moldLedgerEdit') {
        this.checkBtnPermission.moldLedgerEdit = true;
      }
      if (item.code == 'moldLedgerDelBtn') {
        this.checkBtnPermission.moldLedgerDelBtn = true;
      }
      if (item.code == 'moldLedgeView') {
        this.checkBtnPermission.moldLedgeView = true;
      }
    }
  },
  watch: {
    'searchParams.companyId': {
      handler() {
        this.backupId = null;
        this.$set(this.searchParams, 'backupName', null);
        this.backupList = [];
      },
      deep: true,
    },
    'formItem.workShopList': {
      handler() {
        this.formItem.reservoirAreaId = null
        this.formItem.warehouseLocation = null
        const workShopList = this.formItem.workShopList || [];

        if (workShopList.length === 0) {
          console.log('workShopList is empty, skipping request');
          return;
        }

        // 根据长度决定取第一个还是最后一个元素
        const mlocationCode = workShopList.length === 1
            ? workShopList[0]
            : workShopList[workShopList.length - 1];

        console.log('Selected mlocationCode:', mlocationCode);

        request({
          method: 'post',
          url: '/dms/moldStoragelocation/getDeviceTzList',
          data: {
            mlocationCode: [mlocationCode],
            pageNum: 1,
            pageSize: 10
          }
        }).then(res => {
          this.reservoirAreaList = res.data.records
          // 处理响应
        }).catch(error => {
          console.error('Request failed:', error);
        });
      },
      deep: true,
    }
  },
  methods: {
    handleReservoirChange(value) {
      if (value) {
        // 找到选中的库区对象
        const selectedReservoir = this.reservoirAreaList.find(item => item.id === value);
        if (selectedReservoir) {
          // 自动将 mwarehouse 值带出到库位字段
          this.formItem.warehouseLocation = selectedReservoir.mwarehouse;
          this.formItem.reservoirArea = selectedReservoir.mreservoir;
        }
      } else {
        // 清空库区时也清空库位
        this.formItem.warehouseLocation = '';
      }
    },
    handlePrint(record) {
      let arr = [];
      arr.push(record);
      this.$refs.ledgerPrintModal.show(arr, 1);
    },
    // 添加批量打印方法
    batchPrint() {
      if (this.delIds.length === 0) {
        this.$Message.warning('请选择需要打印的记录');
        return;
      }
      // 获取选中的记录
      const selectedRecords = this.dataArr.filter(item => this.delIds.includes(item.id));
      this.$refs.ledgerPrintModal.show(selectedRecords, 1); // 2 表示批量打印模式
    },
    updateStatus(row, status) {
      this.loading = true;
      updateStatusLedgerApi({
        id: row.id,
        status: status
      }).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$Message.success(status === 1 ? '启用成功' : '禁用成功');
          this.searchList();
        } else {
          this.$Message.error(status === 1 ? '启用失败' : '禁用失败');
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    checkMore(row) {
      this.$router.push({
        path: '/moldManagement/moldLedger/moldDetail',
        query: {
          mmoldCode: row.moldCode,
          status: 'detail',
        },
      });
    },
    getSearch(params) {
      this.searchParams = JSON.parse(JSON.stringify(params[0]));
      this.pageNum = 1;
      this.changeNum();
    },
    showMc(row) {
      this.mcRow = row;
      // this.searchMc();

      this.mcShow = true;
    },
    searchMc() {
      this.axios({
        url: '',
        method: 'post',
        data: {
          id: row.id,
          pageNum: this.mcPageNum,
          pageSize: this.mcPageSize,
        },
      }).then((res) => {
        if (res.data.code == 200) {
          this.mcData = res.data.records;
          this.mcTotal = res.data.total;
          this.mcShow = true;
        }
      });
    },
    getOrgList() {
      this.axios({
        method: 'get',
        url: '/basic/organization/findListByToken',
        params: {level: 0},
      }).then((res) => {
        if (res.code === 200) {
          const obj = {
            label: 'name',
            value: 'code',
            children: 'children',
          };
          this.orgList = recursion.convertTree(res.data, obj);
        } else {
          this.$Message.warning({content: res.msg, duration: 6, closable: true});
        }
      });
    },
    keyUp(e, key, money) {
      // 如果是删除为空 则不处理
      if (!this.formItem[key]) {
        return (this.formItem[key] = '');
      }
      // 每次抬键处理,对应金额渲染两位小数||数字
      let num = '';
      if (money) {
        num = this.formItem[key].match(/^\d*(\.?\d{0,2})/g)[0];
      } else {
        num = this.formItem[key].replace(/^[^\d]+$/g, '').split('.')[0];
      }
      this.formItem[key] = `${num}`;
    },
    keyUp5(e, key, money) {
      if (!this.formItem[key]) {
        return (this.formItem[key] = '');
      }
      let num = '';
      if (money) {
        num = this.formItem[key].match(/^\d*(\.?\d{0,5})/g)[0];
      } else {
        num = this.formItem[key].replace(/^[^\d]+$/g, '').split('.')[0];
      }
      this.formItem[key] = `${num}`;
    },
    //获取管理员
    getUserList() {
      getUserSelect()
          .then((res) => {
            if (res.code === 200) {
              this.createByOptions = res.data.map((item) => {
                return {
                  ...item,
                  showName: item.empno + '----' + item.username,
                };
              });
            } else {
              this.createByOptions = [];
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true,
              });
            }
          })
          .finally(() => {
            this.loading = false;
          });
    },
    reset() {
      this.searchParams = {};
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    changeNum2() {
      this.mcPageNum = 1;
      this.searchMc();
    },
    changePageSize2(pageSize) {
      this.mcPageSize = pageSize;
      this.searchMc();
    },
    changePageNum2(val) {
      this.mcPageNum = val;
      this.searchMc();
    },
    //查询列表
    searchList() {
      const {functionalLocationName, moldStateList} = this.searchParams;
      if (functionalLocationName && functionalLocationName.length) {
        this.searchParams.functionalLocationName = [this.searchParams.functionalLocationName.at(-1)];
      } else delete this.searchParams.functionalLocationName;
      if (moldStateList && moldStateList.length == 0) {
        delete this.searchParams.moldStateList;
      }
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams,
      };
      if (params.functionalLocationName && params.functionalLocationName.length != 0) {
        params.functionalLocationName = [params.functionalLocationName.at(-1)];
      } else delete params.functionalLocationName;
      searchApi(params).then((res) => {
        if (res.code === 200) {
          this.dataArr = res.data.records;
          this.total = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    check(row) {
      this.disabled = true;
      this.addtitle = `${this.$t('common.Check')}`;
      this.formItem = JSON.parse(JSON.stringify(row));
      this.create = true;
    },
    //增加或编辑
    createfaultCodeShowH(row) {
      this.disabled = false;
      this.$refs.form.resetFields();
      if (row.id) {
        this.addtitle = `${this.$t('common.Edit')}`;
        this.formItem = JSON.parse(JSON.stringify(row));
      } else {
        this.addtitle = `${this.$t('common.New')}`;
        this.formItem = {
          maintenanceMode: null,
          productionMode: null,
          moldLife: null,
          cavityNum: null,
          score: null,
          lengths: null,
          thickness: null,
          moldingCycle: null,
          externalDimensions: 0,
          manufactureDate: null,
        };
      }
      this.create = true;
    },
    addOk(name) {
      this.$refs[name].validate((valid) => {
        if (!valid) {
          return;
        } else {
          this.loading = true;
          if (this.formItem.id) {
            editApi(this.formItem).then((res) => {
              this.loading = false;
              0;
              if (res.code === 200) {
                this.changeNum();
                this.$Message.success('编辑成功');
                this.create = false;
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true,
                });
              }
            });
          } else {
            addApi(this.formItem).then((res) => {
              this.loading = false;
              if (res.code === 200) {
                this.changeNum();
                this.$Message.success('新增成功');
                this.create = false;
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true,
                });
              }
            });
          }
        }
      });
    },
    //勾选列表
    onSelectChange(selection) {
      let myArray = [];
      selection.map((item, index) => {
        myArray.push(item.id);
      });
      this.delIds = myArray;
      if (selection.length > 0) {
        this.allCheck = true;
      } else {
        this.allCheck = false;
      }
    },
    //批量删除
    delFaultCodeShowClick() {
      if (this.delIds.length == 0) {
        this.$Message.warning({
          content: `${this.$t('common.deleteItems')}`,
          duration: 6,
          closable: true,
        });
        return;
      } else {
        this.delFaultCodeShowF = true;
      }
    },
    //删除
    delPrrShowH(row) {
      //点击展示提示删除弹窗
      this.delFaultCodeShowF = true;
      this.delIds = [];
      this.delIds.push(row.id);
    },
    deleteOk() {
      this.loading = true;
      let params = {delIds: this.delIds};
      deleteApi(params).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          this.changeNum();
          this.$Message.success('删除成功');
          this.allCheck = false;
          this.delFaultCodeShowF = false;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    //下载模板
    exportTemplate() {
      const filName = '模具台账导入模板';
      templateApi().then((res) => {
        fileDownload(res, filName + '.xlsx');
      });
    },
    //导入
    importExcelShow() {
      this.importExcelState = true;
    },
    importExcelChange(val) {
      this.importExcelState = false;
      if (val === 'success') {
        this.changeNum();
      }
    },
    //导出
    exportTemplateClick() {
      let params = {
        delIds: this.delIds,
      };
      for (let key in this.searchParams) {
        if (this.searchParams[key]) {
          this.$set(params, key, this.searchParams[key]);
        }
      }
      const filName = '模具台账';
      exportApi(params).then((res) => {
        fileDownload(res, filName + '.xlsx');
      });
    },
  },
};
</script>

<style scoped lang="scss">
.ivu-input-number {
  width: -webkit-fill-available;
}
</style>
